package maturaarbeit.nicola_pfister.marks;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.google.analytics.tracking.android.EasyTracker;

import maturaarbeit.nicola_pfister.marks.database.DBAdapter;
import android.app.AlertDialog.Builder;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Main extends ListActivity {
	protected Object mActionMode;
	DBAdapter db = new DBAdapter(this);
	
	private String modifitem;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.subjects);
    }
    
    
    
    @Override
	protected void onStart() {
    	EasyTracker.getInstance().activityStart(this);
		super.onStart();
	}



	@Override
	protected void onResume() {
		super.onResume();
		db.open();
		getData();
		
		SharedPreferences prefs = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE);
		
		int firstrun = prefs.getInt("firstrun", 1);
		
		if (firstrun != 0) {
			
			Builder builder = new Builder(this);
			builder
			.setTitle(R.string.dialog_title_welcome)
			.setMessage(R.string.dialog_welcome)
			.setPositiveButton(android.R.string.ok, null)
			.show();
			
			Editor editor = prefs.edit();
			editor.putInt("firstrun", 0).commit();
		}
	}

	@Override
	protected void onPause() {
		db.clean();
		db.close();
		super.onPause();
	}
	
	

	@Override
	protected void onStop() {
		EasyTracker.getInstance().activityStop(this);
		super.onStop();
	}



	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    getMenuInflater().inflate(R.menu.subjects, menu);
	    getMenuInflater().inflate(R.menu.options, menu);
	    return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_add:
			Builder builder = new Builder(this);
			final EditText input = new EditText(this);
			builder
				.setTitle(R.string.dialog_title_addsubject)
				.setMessage(R.string.dialog_addsubject)
				.setView(input)
				.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog, int which) {
						String value = input.getText().toString();
						if (input.getText().toString().trim().length() == 0) {
							Toast.makeText(Main.this, R.string.input_empty, Toast.LENGTH_SHORT).show();
						} else {
							db.insertSubject(value);
							db.insertAverage(value, 0.0);
							getData();
						}
						InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
					}
				})
				.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
	
					public void onClick(DialogInterface dialog, int which) {
						InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
					}
					
				})
				.show();
				input.requestFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
			break;
		case R.id.options_about:
			Builder about = new Builder(this);
			PackageInfo pInfo = null;
			try {
				pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			} catch (NameNotFoundException e) {
				e.printStackTrace();
			}
			String version = pInfo.versionName;
			about
			.setTitle(R.string.dialog_title_about)
			.setMessage("Version " + version + getString(R.string.dialog_about))
			.setPositiveButton(android.R.string.ok, null)
			.setNeutralButton(R.string.feedback, new DialogInterface.OnClickListener() {
	
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent i = new Intent(Intent.ACTION_SEND);
					i.setType("message/rfc822");
					i.putExtra(Intent.EXTRA_EMAIL  , new String[]{getString(R.string.author_email)});
					i.putExtra(Intent.EXTRA_SUBJECT, "Marks Feedback");
					try {
					    startActivity(Intent.createChooser(i, getString(R.string.feedback)));
					} catch (android.content.ActivityNotFoundException ex) {
					    Toast.makeText(Main.this, "There was a problem sending an E-Mail", Toast.LENGTH_SHORT).show();
					}
				}
			})
			.show();
			break;
		case R.id.options_backup:
			final Builder backup = new Builder(this);
			final File sdcard = Environment.getExternalStorageDirectory();
			final String backupdir = sdcard + "/.backup/" + getString(R.string.app_name) + "/";
			final String backupdirfile = backupdir + "database_backup";
			String packageName = getApplicationContext().getPackageName();
			final String databasedir = Environment.getDataDirectory() + "/data/" + packageName + "/databases/";
			final String database = databasedir + "database";
			
			backup
			.setTitle(R.string.dialog_title_backup)
			.setMessage(R.string.dialog_backup)
			.setPositiveButton(R.string.options_backup, new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					final Builder sure = new Builder(Main.this);
					sure
					.setTitle(R.string.dialog_title_sure)
					.setMessage(R.string.dialog_sureb)
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							copyBackup(backupdir, backupdirfile, database);
							
						}
						
					})
					.setNegativeButton(android.R.string.cancel, null)
					.show();
				}
			})
			.setNeutralButton(R.string.restore, new DialogInterface.OnClickListener() {
	
				@Override
				public void onClick(DialogInterface dialog, int which) {
					final Builder sure = new Builder(Main.this);
					sure
					.setTitle(R.string.dialog_title_sure)
					.setMessage(R.string.dialog_surer)
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							File backup = new File (backupdirfile);
							if (backup.exists()) {
								copyBackup(backupdir, database, backupdirfile);
								getData();
							} else {
								Toast.makeText(Main.this, "There is no backup to restore", Toast.LENGTH_SHORT).show();
							}
							
						}
						
					})
					.setNegativeButton(android.R.string.cancel, null)
					.show();
				}
			})
			.setNegativeButton(android.R.string.cancel, null)
			.show();
			break;
		case R.id.options_help:
			Builder help = new Builder(this);
			help
			.setTitle(R.string.options_help)
			.setMessage(R.string.dialog_help)
			.setPositiveButton(android.R.string.ok, null)
			.show();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings("deprecation")
	private void getData() {
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
		        android.R.layout.simple_list_item_activated_1, 
		        db.getAllSubjects(), 
		        new String[] { "subject" }, 
		        new int[] { android.R.id.text1 });
		
		final ListView listView = (ListView) findViewById(android.R.id.list);
		listView.setAdapter(adapter);
		listView.setLongClickable(true);
		listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {

			Cursor cursor = db.getSubject(id);
			String subject = null;
			try {
				subject = cursor.getString(cursor.getColumnIndex("subject"));
			} catch (Exception e) {
				e.printStackTrace();
			}
			Intent intent = new Intent(Main.this, Marks.class);
			intent.putExtra("selected", subject);
			startActivity(intent);
			}
		});
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				listView.clearChoices();
				
				Cursor cursor = db.getSubject(arg3);
				try {
					modifitem = cursor.getString(cursor.getColumnIndex("subject"));
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				if (mActionMode != null) {
					return false;
				}
				
				mActionMode = Main.this
						.startActionMode(mActionModeCallback);
				listView.setItemChecked(arg2, true);
				return true;
			}	
		});
	}

    public void copyBackup(final String backupdir,
			final String target, final String source) {
    	final File sdcard = Environment.getExternalStorageDirectory();
		if (sdcard.canWrite()) {
			
			InputStream input = null;
			try {
				 input = new FileInputStream(source);
			} catch (FileNotFoundException e) {
				Toast.makeText(Main.this, "There was an error finding the database", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
			
			File dir = new File (backupdir);
			if (!dir.exists()) {
			dir.mkdirs();
			}
			OutputStream output = null;
			try {
				 output = new FileOutputStream(target);
			} catch (FileNotFoundException e) {
				Toast.makeText(Main.this, "There was an error creating the backup", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
			
			byte[] buffer = new byte[1024];
			int length;
			try {
				while ((length = input.read(buffer))>0) {
					output.write(buffer, 0, length);
				}
			} catch (IOException e) {
				Toast.makeText(Main.this, "There was an error copying the database", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
			
			try {
				output.flush();
				output.close();
				input.close();
			} catch (IOException e) {
				Toast.makeText(Main.this, "There was an error ending the copy", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
		} else {
			Toast.makeText(Main.this, "No SD card found", Toast.LENGTH_SHORT).show();
		}
	}

	private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
		
		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}
		
		@Override
		public void onDestroyActionMode(ActionMode mode) {
			mActionMode = null;
			
		}
		
		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {
			MenuInflater inflater = mode.getMenuInflater();
			inflater.inflate (R.menu.context, menu);
			return true;
		}
		
		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			switch (item.getItemId()) {
			case R.id.context_edit:
				Builder builder = new Builder(Main.this);
				final EditText input = new EditText(Main.this);
				builder
					.setTitle(getString(R.string.dialog_title_edit) + " " + modifitem)
					.setMessage(R.string.dialog_editsubject)
					.setView(input)
					.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
						
						@SuppressWarnings("unused")
						private double average;

						public void onClick(DialogInterface dialog, int which) {
							String value = input.getText().toString();
							
							if (input.getText().toString().trim().length() == 0) {
								
								Toast.makeText(Main.this, R.string.input_empty, Toast.LENGTH_SHORT).show();
								
							} else {
								db.editSubject(modifitem, value);
								Cursor cursor = db.getAverage(modifitem);
								double average = cursor.getDouble(cursor.getColumnIndexOrThrow(DBAdapter.KEY_VALUE));
								db.editAverage(modifitem, value, average);
								getData();
							}
							InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
							imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
						}
					})
					.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
							imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
						}
					})
					.show();
				input.requestFocus();
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
				mode.finish();
				return true;
			default:
				return false;
				
			case R.id.context_delete:
				Builder alertdialog = new Builder(Main.this);
				alertdialog
					.setTitle(getString(R.string.subject_delete) + " " + modifitem)
					.setMessage(R.string.dialog_deletesubject)
					.setPositiveButton (android.R.string.ok, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
						db.deleteSubject(modifitem);
						getData();
						}
					})
					.setNegativeButton (android.R.string.cancel, null)
					.show();
				mode.finish();
				return true;
			}
			
		}
	};
}